package no.uib.hplims.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;

public class ImportOptimizedValues {

	public boolean startImport(File file) {
		InputStream inputStream = null;

		try {
			inputStream = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			System.out.println("File not found in the specified path.");
			e.printStackTrace();
		}

		POIFSFileSystem fileSystem = null;

		try {
			fileSystem = new POIFSFileSystem(inputStream);
			HSSFWorkbook workBook = new HSSFWorkbook(fileSystem);

			int numSheets = workBook.getNumberOfSheets();

			for (int i = 0; i < numSheets; i++) {
				HSSFSheet sheet = workBook.getSheetAt(i);

				String orderNumber = sheet.getSheetName().split(",")[0];
				System.out.println("Order number: " + orderNumber);

				Iterator<Row> rows = sheet.rowIterator();
				while (rows.hasNext()) {
					HSSFRow row = (HSSFRow) rows.next();

					if (row.getRowNum() >= 1) {
						if (row.getCell(0) != null) {
							double q1 = row.getCell(0).getNumericCellValue();
							double q3 = row.getCell(1).getNumericCellValue();
							double dwell = row.getCell(2).getNumericCellValue();
							String peptide = row.getCell(3)
									.getStringCellValue();
							double dp = row.getCell(4).getNumericCellValue();
							double ep = row.getCell(5).getNumericCellValue();
							double ce = row.getCell(6).getNumericCellValue();
							double cxp = row.getCell(7).getNumericCellValue();

							// TODO: store data in db
						}
					}
				}

			}

			// close inputstream when finished
			if (inputStream != null) {
				inputStream.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

}
